<?php

namespace App\Models;

use Illuminate\Support\Facades\DB;

class DiningReserveProd extends Base
{
    //根据订单ID获取订单商品信息
    public function getProdDetails($orderid){
        try{

            $result = Db::table('dining_reserve_prods')
                     ->leftJoin('dining_reserves','dining_reserves.id','=','dining_reserve_prods.did')
                     ->leftJoin('products','dining_reserve_prods.proid','=','products.id')
                     ->select('dining_reserve_prods.*','dining_reserves.ordersn','products.proname','products.proname_zn','products.image')
                     ->where('did',$orderid)->orderBy('dining_reserve_prods.created_at','desc')->get()->toArray();
            return ['code'=>0,'data'=>$result];
        }catch (\Exception $e){
            return [
                'code'=>1,
                'message'=>$e->getMessage()
            ];
        }
    }

    //新增预定订单商品
    public function oneInsert($data=array(),$type="admin"){
        try {
            //获取当前订单状态及类型
            $dinorder = DiningReserve::find($data['did']);
            //如果已结账或退订，则不可添加
            if($dinorder->status>=4){
                return [
                    'code'=>1,
                    'message'=>'该订单不可操作'
                ];
            }
            $user = (new User())->where('id',$dinorder->uid)->select('total','deleted_at')->first();
            $total = $user->total;
            if($user->deleted_at){
                return [
                    'code'=>1,
                    'message'=>'用户已禁用,不可操作'
                ];
            }
            //获取该用户等级
            $levid = (new UserLevel())->where([
                ['min','<=',$total],['max','>',$total]
            ])->value('id');
            if($type=='admin'){ //后台添加商品
                $status = isset($data['status'])?$data['status']:2;
            }else{ //前台添加商品
                $status = 0;
            }
            $prods = json_decode($data['prods'],true);
            if(empty($prods)){
                return [
                    'code'=>1,
                    'message'=>'商品信息为空'
                ];
            }
            $insertData = [];//需要插入商品库的数据
            $now = date('Y-m-d H:i:s');
            foreach ($prods as $key=>$pd){
                //获取商品价格
                $prod = (new Product())->where('id',$pd['proid'])->select('rprice','deleted_at')->first();
                if($prod->deleted_at){
                    return [
                        'code'=>1,
                        'message'=>'该商品已下架,不可添加'
                    ];
                }
                $price = $prod->rprice;
                //获取该用户在该商品中的折扣
                $discount = (new ProdDiscount())->where([
                    ['proid','=',$pd['proid']],['levid','=',$levid]
                ])->value('discount');
                if($discount){
                    $price = $price * $discount / 100;
                }
                $insertData[$key]['did'] = $data['did'];
                $insertData[$key]['proid'] = $pd['proid'];
                $insertData[$key]['pronum'] = $pd['pronum'];
                $insertData[$key]['status'] = $pd['status'];
                $insertData[$key]['proprice'] = $price;
                $insertData[$key]['created_at'] =$now;
                $insertData[$key]['updated_at'] =$now;
            }
            $dinorder->total = $dinorder->total + $price;
            $that = $this;
            DB::transaction(function()use($insertData,$that,$dinorder){
                $that->insert($insertData);
                $dinorder->save();
            },5);
            return [
                'code'=>0,
                'data'=>''
            ];
        }catch (\Exception $e){
            return [
                'code'=>1,
                'message'=>$e->getMessage()
            ];
        }
    }

    //预定订单商品退订
    public function oneDelete($id=0){
        try{
            //获取商品订单信心
            $promodel = self::find($id);
            //获取当前订单用户及状态
            $dinorder = DiningReserve::find($promodel->did);
            //如果已结账或退订，则不可添加
            if($dinorder->status>=4){
                return [
                    'code'=>1,
                    'message'=>'该订单不可操作'
                ];
            }
            $isuser = (new User())->where('id',$dinorder->uid)->value('deleted_at');
            if($isuser){
                return [
                    'code'=>1,
                    'message'=>'用户已禁用,不可操作'
                ];
            }
            $hasProd = $this->where('did',$promodel->did)->get();
            if(!$hasProd){
                return [
                    'code'=>1,
                    'message'=>'订单至少得保留一个商品'
                ];
            }
            $proprice = $promodel->proprice * $promodel->pronum;
            $dinorder->total -= $proprice;
            $promodel->status = 4;
            DB::transaction(function ()use ($promodel,$dinorder){
                $promodel->save();
                $dinorder->save();
            },5);
            return [
                'code'=>0,
                'data'=>''
            ];
        }catch (\Exception $e){
            return [
                'code'=>1,
                'message'=>$e->getMessage()
            ];
        }
    }

    //改变订单商品状态
    public function changeStatus($data=array()){
        try{
            $order = self::findOrFail($data['id']);
            $cando = true;
            $where = [];
            $update = [];
            switch($data['status']) {
                //付款成功操作,将所有申请中的商品变成待审核(1)
                case 1:
                    $cando =  $order->status === 0?true:false;
                    $where[] = ['status','=',0];
                    $update = ['status'=>1];
                    break;
                //后台接单操作,将所有待审核的商品变成待付款(2)
                case 2:
                    $cando =  $order->status === 1?true:false;
                    $where[] = ['status','=',1];
                    $update = ['status'=>2];
                    break;
                //后台到场操作,商品状态无需改变
                case 3:
                    $cando =  $order->status === 2?true:false;
                    $where[] = ['status','=',2];
                    $update = ['status'=>2];
                    break;
                //后台退订,改变所有待付款的商品为退订
                case 5:
                    $cando =  ($order->status === 2 || $order->status === 3)?true:false;
                    $where[] = ['status','=',2];
                    $update = ['status'=>4];
                    break;
                //取消订单,
                case 6:
                    $cando = ($order->status === 1 || $order->status === 0)?true:false;
                    $where[] = ['status','=',1];
                    $update = ['status'=>6];
            }
            if(!$cando){
                return [
                    'code'=>1,
                    'message'=>'该操作有误'
                ];
            }
            $promodel = new DiningReserveProd();
            $order->status = $data['status'];
            $update['updated_at'] = date('Y-m-d H:i:s');
            DB::transaction(function ()use($promodel,$order,$where,$update){
                $order->save();
                $promodel->where($where)->update($update);
            },5);
            return [
                'code'=>0,
                'data'=>$data['id']
            ];
        }catch (\Exception $e){
            return [
                'code'=>1,
                'message'=>$e->getMessage()
            ];
        }

    }
}
